// 链接安全检测模块
const LinkSafetyManager = {
    // 调用后端API进行安全检测（包含本地和远程检测）
    checkUrlSafety: async function(url) {
        try {
            // 调用后端API（后端会同时执行本地和远程检测）
            const response = await Api.apiRequest('/link-safety/check', {
                method: 'POST',
                body: JSON.stringify({ url: url })
            });

            return response;
        } catch (error) {
            console.error('链接安全检测失败:', error);
            return null;
        }
    },

    // 显示链接确认弹窗
    showLinkConfirmDialog: async function(url) {
        return new Promise(async (resolve) => {
            const content = `
                <div class="link-confirm-dialog">
                    <div class="link-info">
                        <div class="link-url-container">
                            <textarea id="link-url-textarea" class="link-url-text" readonly onclick="LinkSafetyManager.copyLinkText(this)">${url}</textarea>
                        </div>
                    </div>
                    <div class="link-safety-checking" id="safety-check-status">
                        <i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i>
                        正在进行安全检测...
                    </div>
                    <div id="safety-check-result" style="display: none;"></div>
                    <div class="link-warning">
                        <i class="layui-icon layui-icon-tips"></i>
                        请谨慎访问未知链接，防止钓鱼和恶意软件
                    </div>
                </div>
            `;

            // 检测是否为移动端
            const isMobile = window.innerWidth <= 768;
            
            const layerIndex = layui.layer.open({
                type: 1,
                title: '链接安全确认',
                area: isMobile ? ['100%', '100%'] : ['600px', 'auto'],
                content: content,
                btn: ['打开链接', '取消'],
                btnAlign: 'c',
                yes: function(index) {
                    layui.layer.close(index);
                    resolve(true);
                },
                btn2: function(index) {
                    layui.layer.close(index);
                    resolve(false);
                },
                cancel: function() {
                    resolve(false);
                },
                success: function() {
                    // 弹窗打开后，显示tips提示
                    const textarea = document.getElementById('link-url-textarea');
                    if (textarea) {
                        layui.layer.tips('点击复制链接', textarea, {
                            tips: [1, '#01AAED'],
                            time: 2000
                        });
                    }
                    
                    // 异步进行安全检测
                    LinkSafetyManager.performSafetyCheck(url);
                }
            });
        });
    },

    // 执行安全检测（支持轮询）
    performSafetyCheck: async function(url, retryCount = 0) {
        const checkingDiv = document.getElementById('safety-check-status');
        const resultDiv = document.getElementById('safety-check-result');
        
        if (!checkingDiv || !resultDiv) return;
        
        // 如果是重试，显示重试次数
        if (retryCount > 0) {
            checkingDiv.style.display = 'block';
            checkingDiv.innerHTML = `
                <i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i>
                正在检测中... (第${retryCount}次重试)
            `;
            resultDiv.style.display = 'none';
        }
        
        const result = await this.checkUrlSafety(url);
        
        checkingDiv.style.display = 'none';
        resultDiv.style.display = 'block';
        
        if (result && result.local_check && result.remote_check) {
            const local = result.local_check;
            const remote = result.remote_check;
            
            // 判断安全等级
            const localSafe = local.status === 'safe';
            const remoteSafe = remote.status === 'safe';  // 只有明确的safe才算安全
            const remoteUnknown = remote.status === 'unknown';  // 未知状态
            const remoteError = remote.status === 'error';  // 错误状态（需要重试）
            
            let statusClass = '';
            let bgColor = '';
            let borderColor = '';
            
            if (!localSafe && !remoteSafe && !remoteUnknown && !remoteError) {
                // 两个都不通过（明确危险）- 危险
                statusClass = 'link-safety-danger';
                bgColor = '#fff5f5';
                borderColor = '#FF5722';
            } else if (!localSafe || !remoteSafe || remoteUnknown || remoteError) {
                // 本地不通过 或 远程不通过 或 远程未知 或 远程错误 - 警告
                statusClass = 'link-safety-warning';
                bgColor = '#fffbf0';
                borderColor = '#FFB800';
            } else {
                // 都明确通过 - 安全
                statusClass = 'link-safety-safe';
                bgColor = '#f0f9ff';
                borderColor = '#5FB878';
            }
            
            // 构建显示内容
            const localColor = localSafe ? '#5FB878' : '#FF5722';
            const remoteColor = remoteSafe ? '#5FB878' : '#FF5722';
            
            const localIcon = localSafe ? '✓' : '✗';
            const remoteIcon = remoteSafe ? '✓' : (remoteUnknown || remoteError ? '?' : '✗');
            
            // 构建报告链接HTML
            let reportLinkHtml = '';
            if (remote.report_url) {
                reportLinkHtml = `
                    <div style="margin-top: 12px; padding-top: 10px; border-top: 1px solid rgba(0,0,0,0.1); text-align: center;">
                        <a href="${remote.report_url}" target="_blank" style="color: #01AAED; text-decoration: none; font-size: 13px;">
                            <i class="layui-icon layui-icon-link"></i> 查看完整VirusTotal报告
                        </a>
                    </div>
                `;
            }
            
            resultDiv.innerHTML = `
                <div class="link-safety-status ${statusClass}" style="background-color: ${bgColor}; border-color: ${borderColor};">
                    <div style="margin-bottom: 8px;">
                        <span style="color: ${localColor}; font-weight: bold;">${localIcon} 本地检测:</span>
                        <span style="color: ${localColor};">${local.message || local.reason}</span>
                    </div>
                    <div>
                        <span style="color: ${remoteColor}; font-weight: bold;">${remoteIcon} 远程检测:</span>
                        <span style="color: ${remoteColor};">${remote.message || '检测完成'}</span>
                    </div>
                    ${reportLinkHtml}
                </div>
            `;
            
            // 如果远程检测状态为unknown（扫描中）或error（超时/失败），启动轮询（最多重试20次）
            if ((remote.status === 'unknown' || remote.status === 'error') && retryCount < 20) {
                const reason = remote.status === 'unknown' ? '扫描中' : '请求失败';
                const delay = remote.status === 'error' ? 10000 : 5000;  // 错误状态延迟5秒，未知状态延迟3秒
                
                setTimeout(() => {
                    this.performSafetyCheck(url, retryCount + 1);
                }, delay);
            } else if ((remote.status === 'unknown' || remote.status === 'error') && retryCount >= 20) {
                console.error('已达到最大重试次数(20次)，停止轮询');
            }
        } else {
            resultDiv.innerHTML = '<div class="link-safety-checking">检测服务暂时不可用</div>';
        }
    },

    // 复制链接文本（点击textarea）
    copyLinkText: function(textarea) {
        const text = textarea.value;
        
        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(text).then(() => {
                layui.layer.msg('链接已复制到剪贴板', { icon: 1, time: 1500 });
                textarea.select();
            }).catch(err => {
                console.error('复制失败:', err);
                layui.layer.msg('复制失败，请手动复制', { icon: 2 });
                textarea.select();
            });
        } else {
            // 降级方案：选中文本
            textarea.select();
            try {
                document.execCommand('copy');
                layui.layer.msg('链接已复制到剪贴板', { icon: 1, time: 1500 });
            } catch (err) {
                console.error('复制失败:', err);
                layui.layer.msg('请手动复制', { icon: 0 });
            }
        }
    },

    // 复制到剪贴板（保留，以防其他地方使用）
    copyToClipboard: function(text, button) {
        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(text).then(() => {
                const originalHtml = button.innerHTML;
                button.innerHTML = '<i class="layui-icon layui-icon-ok"></i> 已复制';
                button.disabled = true;
                
                setTimeout(() => {
                    button.innerHTML = originalHtml;
                    button.disabled = false;
                }, 2000);
            }).catch(err => {
                console.error('复制失败:', err);
                layui.layer.msg('复制失败，请手动复制');
            });
        } else {
            // 降级方案：使用传统方法
            const textarea = document.createElement('textarea');
            textarea.value = text;
            textarea.style.position = 'fixed';
            textarea.style.opacity = '0';
            document.body.appendChild(textarea);
            textarea.select();
            
            try {
                document.execCommand('copy');
                const originalHtml = button.innerHTML;
                button.innerHTML = '<i class="layui-icon layui-icon-ok"></i> 已复制';
                button.disabled = true;
                
                setTimeout(() => {
                    button.innerHTML = originalHtml;
                    button.disabled = false;
                }, 2000);
            } catch (err) {
                console.error('复制失败:', err);
                layui.layer.msg('复制失败，请手动复制');
            }
            
            document.body.removeChild(textarea);
        }
    },

    // 提取onclick中的URL
    extractUrlFromOnclick: function(onclickStr) {
        if (!onclickStr) return null;
        
        // 匹配 window.open('url') 或 window.open("url") 或 window.open(url)
        const patterns = [
            /window\.open\s*\(\s*['"]([^'"]+)['"]/i,  // window.open('url')
            /window\.open\s*\(\s*([^'")[,\s]+)/i      // window.open(url)
        ];
        
        for (const pattern of patterns) {
            const match = onclickStr.match(pattern);
            if (match && match[1]) {
                return match[1].trim();
            }
        }
        
        return null;
    },

    // 拦截iframe中的链接点击
    interceptIframeLinks: function(iframeElement) {
        try {
            const iframe = iframeElement[0] || iframeElement;
            
            iframe.addEventListener('load', function() {
                try {
                    const iframeDoc = this.contentDocument || this.contentWindow.document;
                    
                    // 给所有链接添加点击事件监听器（使用捕获阶段）
                    const links = iframeDoc.querySelectorAll('a[href]');
                    links.forEach(link => {
                        // 使用捕获阶段，确保在子元素之前拦截
                        link.addEventListener('click', async function(e) {
                            e.preventDefault();
                            e.stopPropagation();
                            e.stopImmediatePropagation();
                            
                            let href = this.getAttribute('href');
                            const onclick = this.getAttribute('onclick');
                            
                            // 如果href是javascript:开头，尝试从onclick中提取真实URL
                            if (href && (href.startsWith('javascript:') || href === '#' || href.startsWith('#'))) {
                                const extractedUrl = LinkSafetyManager.extractUrlFromOnclick(onclick);
                                if (extractedUrl) {
                                    console.log('从onclick提取到URL:', extractedUrl);
                                    href = extractedUrl;
                                } else if (href.startsWith('javascript:') || href === '#') {
                                    // 如果是javascript:但没有提取到URL，忽略该链接
                                    console.log('忽略javascript伪协议链接');
                                    return;
                                }
                            }
                            
                            // 忽略空链接
                            if (!href) {
                                return;
                            }
                            
                            // 忽略mailto链接
                            if (href.startsWith('mailto:')) {
                                window.location.href = href;
                                return;
                            }
                            
                            // 处理相对路径，转换为绝对路径
                            let absoluteUrl = href;
                            if (!href.startsWith('http://') && !href.startsWith('https://')) {
                                try {
                                    absoluteUrl = new URL(href, window.location.href).href;
                                } catch (error) {
                                    console.error('URL解析失败:', error);
                                    absoluteUrl = href;
                                }
                            }
                            
                            // 显示确认弹窗
                            const confirmed = await LinkSafetyManager.showLinkConfirmDialog(absoluteUrl);
                            
                            if (confirmed) {
                                window.open(absoluteUrl, '_blank');
                            }
                        }, true); // 使用捕获阶段
                        
                        // 阻止所有子元素的点击事件冒泡
                        const children = link.querySelectorAll('*');
                        children.forEach(child => {
                            child.addEventListener('click', function(e) {
                                e.preventDefault();
                                e.stopPropagation();
                                // 触发父链接的点击
                                link.click();
                            }, true);
                        });
                    });
                    
                    console.log(`已拦截 ${links.length} 个链接`);
                } catch (error) {
                    console.error('无法访问iframe内容，可能是跨域限制:', error);
                }
            });
        } catch (error) {
            console.error('链接拦截设置失败:', error);
        }
    }
};

// 添加样式
if (!document.getElementById('link-safety-styles')) {
    const style = document.createElement('style');
    style.id = 'link-safety-styles';
    style.textContent = `
        .link-confirm-dialog {
            padding: 20px;
        }

        .link-info {
            margin-bottom: 20px;
        }

        .link-url-container {
            position: relative;
            width: 100%;
        }

        .link-url-text {
            width: 100%;
            min-height: 80px;
            padding: 12px;
            border: 1px solid #e6e6e6;
            border-radius: 4px;
            font-family: 'Courier New', monospace;
            font-size: 13px;
            resize: vertical;
            background-color: #f8f8f8;
            cursor: pointer;
            transition: all 0.3s;
            box-sizing: border-box;
            word-wrap: break-word;
            word-break: break-all;
        }

        .link-url-text:hover {
            border-color: #01AAED;
            background-color: #f0f9ff;
        }

        .link-url-text:focus {
            outline: none;
            border-color: #01AAED;
            background-color: #fff;
        }

        .link-safety-status {
            padding: 12px 15px;
            margin: 15px 0;
            border-radius: 4px;
            font-size: 14px;
        }

        .link-safety-safe {
            background-color: #f0f9ff;
            border: 1px solid #5FB878;
            color: #5FB878;
        }

        .link-safety-warning {
            background-color: #fffbf0;
            border: 1px solid #FFB800;
            color: #D68300;
        }

        .link-safety-danger {
            background-color: #fff5f5;
            border: 1px solid #FF5722;
            color: #FF5722;
        }

        .link-safety-info {
            background-color: #f0f9ff;
            border: 1px solid #01AAED;
            color: #01AAED;
        }

        .link-safety-checking,
        .link-safety-result {
            padding: 12px 15px;
            margin: 15px 0;
            border-radius: 4px;
            background-color: #f8f8f8;
            font-size: 13px;
            text-align: center;
        }

        .link-warning {
            margin-top: 15px;
            padding: 12px 15px;
            background-color: #fff9e6;
            border-left: 3px solid #FFB800;
            font-size: 13px;
            color: #666;
        }

        /* 手机端适配 */
        @media screen and (max-width: 768px) {
            .link-confirm-dialog {
                padding: 15px;
            }
            
            .link-url-text {
                min-height: 100px;
                font-size: 12px;
            }
        }

        .link-warning i {
            color: #FFB800;
            margin-right: 5px;
        }
    `;
    document.head.appendChild(style);
}